import Vue from 'vue';
import Router from 'vue-router';
import { Message } from 'element-ui';
import $store from '@/store';
import { $rp } from '@/utils/constants';
import Homepage from '@/views/homepage';
import NotFound from '@/components/errors/NotFound';
import Announcements from '@/views/announcements';

import users from './users';
import spaces from './spaces';
import groups from './groups';
import questionnaires from './questionnaires';
import feedback from './feedback';
import webAdmin from './web_admin';
import other from './other';

import communities from './communities';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      component: Homepage,
    },
    ...users,
    ...spaces,
    ...groups,
    ...questionnaires,
    ...feedback,
    ...communities,
    ...other,
    {
      path: `/${$rp.ANNOUNCEMENTS}`,
      component: Announcements,
      meta: { hideHeaderReminder: true },
    },
    ...webAdmin,
    {
      path: '*',
      name: 'NotFound',
      component: NotFound,
    },
  ],
});

const unwantedAuthRouterList = [ // 不需要登录的路由（因为meta不能定位到某一个alias）
  '/spaces',
  '/spaces/all',
];
const isRequireAuth = path => !unwantedAuthRouterList.includes(path);

router.beforeEach((to, from, next) => {
  const currentUser = $store.state.currentUser;
  const logged = Object.keys(currentUser).length;
  if (!logged && to.meta.requireAuth && isRequireAuth(to.path)) {
  // if (!logged && to.meta.requireAuth && isRequireAuth(to.path)) {
    Message.warning('请登录后继续');
    next({ path: `/${$rp.USERS}/${$rp.SIGN_IN}`, query: { redirect: to.fullPath } });
  } else next();
});

export default router;
